<template>
  <el-dialog :title="textCommodity[diaCommodityStatus]" :visible.sync="dialogCommodityVisible" :show-close="false"
    class="Commodityproduct">
    <el-form :model="CommodityFormList" :rules="Commodityrules" ref="CommodityFormList" label-width="120px"
      class="demo-ruleForm" @click.stop>
      <el-form-item label="组合商品名称" prop="name">
        <el-input v-model.trim="CommodityFormList.name" style="width:200px" size="small" type="textarea" maxlength="64"
          show-word-limit :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
      </el-form-item>
      <el-form-item label="蛋糕类型" required>
        <el-cascader ref="cascaderAddr" v-model="selectedValue" :options="cakelist" clearable
          @change="handelcategoryzeName" @visible-change="getcakelist"></el-cascader>
      </el-form-item>
      <el-form-item label="商品原料" v-show="materialsShow" required>
        <ele-multi-cascader clearable v-model="materialslistValue" :options="materialslist" separator=">"
          placeholder="选择商品原料" @change="handlematerialzhName" style="width: 194px;"></ele-multi-cascader>
      </el-form-item>
      <el-form-item label="商品主图:" prop="mainPic" required>
        <div style="margin-bottom: 15px;">
          <div style="margin-bottom: 15px;">
            <el-upload list-type="picture-card" action="/api/xmbz-goods/file/upload" :show-file-list="false"
              :data="{ tag: 'good' }" :on-success="handleCombinedSuccess">
              <img v-if="CommodityFormList.mainPic" :src="CommodityFormList.mainPic" class="avatar">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品副图:" prop="title">
        <div style="margin-bottom: 15px;">
          <el-upload action="/api/xmbz-goods/file/upload" :data="{ tag: 'good' }" :on-exceed="handleExceed"
            list-type="picture-card" :on-success="handlezhfuSuccess" :limit="4" :file-list="CommodityFormList.pics"
            :on-remove="beforezhRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="商品详情:">
        <el-input type="textarea" size="small" v-model.trim="CommodityFormList.description" style="width:400px"
          maxlength="300" show-word-limit :autosize="{ minRows: 6, maxRows: 8 }"></el-input>
      </el-form-item>
      <hr>
      <div class="specifications">
        <h2>组合选项</h2>
        <el-form-item label="商品名称" prop="goodsCombinationList" style="position:relative" v-clickoutside="hideSearchBox">
          <el-input v-model="CommodityFormList.commodityserch" style="width:200px" size="small" placeholder="请输入商品名称搜索"
            @input="handlecommodityserch(CommodityFormList.commodityserch)" @focus="showSearchBox"></el-input>
          <div v-if="CommodityFormList.goodsCombinationList">
            <span
              style="margin-right:10px ;"
              v-if=" CommodityFormList.goodsCombinationList&& CommodityFormList.goodsCombinationList.length"
            >已选：</span>
            <el-tag
              class="mr-5"
              v-for="(tag,index) in CommodityFormList.goodsCombinationList"
              :key="index"
              closable
              :disable-transitions="false"
              @close="handlegoodListClose(tag,index)"
            >{{tag.zuGoodsName}}~{{tag.zuSpecs}}</el-tag>
          </div>

          <div class="specificationsslist" v-if="commodityserchshow">
            <el-tabs tab-position="left" style="height: 200px;">
              <el-tab-pane v-for="(item, index) in combinedData" :key="index" :label="item.name">
                <p v-for="(child2, index2) in item.goodsSkuList" :key="index2" class="cs-p"
                  @click="handleGoodsList(item.name, child2.specs, child2.id)" style="120px">{{ child2.specs }}</p>
              </el-tab-pane>
            </el-tabs>
            <div class="close">
              <i class="el-icon-error Delgoodlist" @click="headleclose"></i>
            </div>
          </div>
        </el-form-item>
        <div class="lows">
          <el-form-item label="sku码">
            <el-input size="small" v-model.trim="CommodityFormList.skuCode" :min="0" style="width:100px"
              onkeyup="value=value.replace(/[^\-?\d.a-zA-Z]/g,'').slice(0,20)" maxlength="20"
              onafterpaste="value=value.replace(/[^\-?\d.a-zA-Z]/g,'').slice(0,20)"></el-input>
          </el-form-item>
          <el-form-item label="upc码">
            <el-input size="small" type="number" v-model.trim="CommodityFormList.upc" :min="0" style="width:100px"
              maxlength="50" onkeyup="value=value.replace(/[^\d]|^[0]/g,'').slice(0,50)"
              onafterpaste="value=value.replace(/[^\d]|^[0]/g,'').slice(0,50)"></el-input>
          </el-form-item>
          <el-form-item label="定价(元)">
            <el-input size="small" type="number" v-model.trim="CommodityFormList.price" :min="0"
              oninput="if(value.length>7)value=value.slice(0,7)" style="width:100px"></el-input>
          </el-form-item>
          <el-form-item label="商品状态">
            <el-radio-group v-model="CommodityFormList.goodsState">
              <el-radio :label="1">可售</el-radio>
              <el-radio :label="2">不可售</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handelDialogResetCommodity()">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  Categories, // 商品类型
  GoodsMaterial, //商品原料
  addGoods, //添加商品
  searchGoodsList, //搜索
  GoodsInfo, //详情
  goodsUpdate //更新提交
} from "@/api/commodityfiles";
import Clickoutside from 'element-ui/src/utils/clickoutside'

export default {
  directives: {
    Clickoutside
  },
  props: {
    clickFramingchecked: {
      type: Boolean
    }
  },
  data() {
    return {
      //组合商品------------------------------------------------------------
      combinedData: [],
      Commoditymaterials: "",

      textCommodity: {
        update: "修改组合商品",
        create: "添加组合商品",
        copy: "复制组合商品",
      },
      dialogCommodityVisible: false, //组合商品
      caketype: false,
      materials: false,
      diaCommodityStatus: "",
      SingleproductForm: {
        name: "",
        cakeType: "",
        categoryId: "",
        categoryName: "",
        materialId: "",
        Commoditymaterials: "", // 商品原料
        mainPic: "", //  主图
        pics: [], //附图
        description: "",
        isOnSale: "",
        goodsSkuRequests: [
          {
            specs: "", //规格名
            price: "", // 定价
            skuCode: "", // sku 码
            upc: "", // uPc
            goodsState: 1, //商品状态
            isCombination: 1,
            goodsSkuProduction: null,
            materielState: 2
          }
        ]
      },
      Commodityrules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur"
          }
        ],
        commodityserch: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "change"
          }
        ],
        mainPic: [
          {
            required: true,
            message: "请上传商品主图",
            trigger: "blur"
          }
        ],
        Commoditymaterials: [
          {
            required: true,
            message: "请至少选择一个商品原料",
            trigger: "change"
          }
        ],
        specs: [
          {
            required: true,
            message: "请输入商品规格",
            trigger: "blur"
          }
        ],
        skuCode: [
          {
            required: true,
            message: "请输入商品sku码",
            trigger: "blur"
          }
        ],
        upc: [
          {
            required: true,
            message: "请输入商品upc码",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "请输入商品定价",
            trigger: "blur"
          }
        ]
      },
      materialslist: [],
      materialslists: [],
      combinedDataName: [], // 组合数据
      checkedmaterialslist: [],
      cakelist: [],
      // 组合商品
      commodityserchshow: false,
      CommodityFormList: {
        name: "",
        cakeType: "",
        categoryId: "",
        materialId: "",
        description: "",
        Commoditymaterials: "", // 商品原料
        mainPic: "", //  主图
        pics: [], //附图
        commodityserch: "",
        goodsState: 1, //商品状态
        goodsCombinationList: [], //组合数据
        price: "", // 定价
        skuCode: "", // sku 码
        upc: "", // uPc
        zuModifyPrice: "",
        isOnSale: ""
      },
      cityareaId: "",
      materialName: "",
      selectedValue: [],
      materialslistValue: [],
    };
  },
  computed: {
    materialsShow() {
      return this.selectedValue && this.selectedValue.includes('1670323326059520')
    }
  },
  methods: {
    show({ status, data }) {
      this.diaCommodityStatus = status;
      this.dialogCommodityVisible = true;
      this.getcakelist(); //查蛋糕类型
      this.initInfo();
      this.goodsInfo = data || {}
      if (data) {
        this.getGoodsInfo(data)
      }
      this.$refs['CommodityFormList'] && this.$refs['CommodityFormList'].resetFields();
    },
    getGoodsInfo(item) {
      GoodsInfo({
        goodsId: item.id
      }).then(response => {
        var materialIdlsit = []
        this.CommodityFormList.name = response.data.data.name;
        this.CommodityFormList.categoryId =
          response.data.data.categoryId;
        this.CommodityFormList.id = response.data.data.id;
        this.CommodityFormList.mainPic = response.data.data.mainPic;
        this.CommodityFormList.description =
          response.data.data.description;
        this.selectedValue = [item.parentCategoryId, item.categoryId]
        this.CommodityFormList.pics = response.data.data.goodsPicList;
        this.checkedmaterialslist =
          response.data.data.goodsRelationMaterialVOList;
        this.checkedmaterialslist.map(child => {
          materialIdlsit.push(child.materialId);
        });
        this.materialslistValue = materialIdlsit;
        this.CommodityFormList.goodsCombinationList =
          response.data.data.goodsCombinationList;
        this.CommodityFormList.pics.map(child => {
          child.url = child.pic;
        });
        if (
          this.CommodityFormList.goodsCombinationList &&
          this.CommodityFormList.goodsCombinationList.length
        ) {
          this.CommodityFormList.skuCode = this.CommodityFormList.goodsCombinationList[0].zuSkuCode;
          this.CommodityFormList.price = this.CommodityFormList.goodsCombinationList[0].zuModifyPrice;
          this.CommodityFormList.upc = this.CommodityFormList.goodsCombinationList[0].zuUpc;
          this.CommodityFormList.goodsState = this.CommodityFormList.goodsCombinationList[0].zuGoodsState;
        }
        this.combinedData = response.data.data.goodsCombinationList; //组合 查询数据
      });
    },
    initInfo() {
      this.selectedValue = [];
      this.materialslistValue = [];
      this.CommodityFormList.commodityserch = '';
      this.CommodityFormList = {
        name: "",
        cakeType: "",
        categoryId: "",
        materialId: "",
        description: "",
        Commoditymaterials: "", // 商品原料
        mainPic: "", //  主图
        pics: [], //附图
        commodityserch: "",
        goodsState: 1, //商品状态
        goodsCombinationList: [], //组合数据
        price: "", // 定价
        skuCode: "", // sku 码
        upc: "", // uPc
        zuModifyPrice: ""
      };
    },
    handelcategoryzeName(item) {
      this.CommodityFormList.categoryId = item[1];
      var str = [];
      this.cakelist.map(parent => {
        parent.children.map(child => {
          if (item[1] === child.value) {
            str.push(child);
          }
        });
      });
    },
    getcakelist() {
      Categories("").then(response => {
        // this.cakelist = response.data.data;
        const batchdata = response.data.data;
        const dataValueBatch = batchdata =>
          batchdata.map(
            ({ id, categoryName, children }) =>
              children
                ? {
                  value: id,
                  label: categoryName,
                  children: dataValueBatch(children)
                }
                : {
                  value: id,
                  label: categoryName
                }
          );
        this.cakelist = dataValueBatch(batchdata);
      });
    },
    handlecommodityindexClose(tag, index) {
      this.checkedmaterialslist.splice(index, 1);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 4 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforezhRemove(index) {
      this.CommodityFormList.pics.splice(index, 1);
    },
    // 组合
    handleCombinedSuccess(response) {
      this.CommodityFormList.mainPic = response.data;
    },
    // 组合幅图上传
    handlezhfuSuccess(response) {
      this.CommodityFormList.pics.push({
        url: response.data
      });
    },
    // 组合
    handlecommodityserch(name) {
      searchGoodsList({
        deptId: this.clickFramingchecked == true ? "1" : this.cityareaId,
        name: name
      }).then(response => {
        this.combinedData = response.data.data;
        if (!this.combinedData || !this.combinedData.length) {
          this.$message("无此商品名称请重新输入");
        }
      });
    },
    showSearchBox() {
      console.log('showSearchBox')
      this.commodityserchshow = true
    },
    hideSearchBox() {
      console.log('hideSearchBox')
      this.commodityserchshow = false
    },
    handleGoodsList(name, specs, skuId) {
      if (this.CommodityFormList.goodsCombinationList.length < 20) {
        this.CommodityFormList.goodsCombinationList.push({
          zuGoodsId: skuId,
          zuGoodsName: name,
          zuSpecs: specs
        });
        this.commodityserchshow = false;
      } else {
        this.$message({
          message: "该商品规格最多可添加20个",
          type: "warning"
        });
        return false;
      }
    },
    headleclose() {
      this.commodityserchshow = false;
    },
    handelDialogResetCommodity() {
      //取消组合页面
      this.dialogCommodityVisible = false;
    },
    handleConfirm() {
      if (this.diaCommodityStatus === 'create' || this.diaCommodityStatus === 'copy') {
        this.createcommodityData(this.CommodityFormList, 'CommodityFormList')
      } else if (this.diaCommodityStatus === 'update') {
        this.updatecommodityData(this.CommodityFormList, 'CommodityFormList')
      }
    },
    createcommodityData(item, verification) {
      this.$refs[verification].validate(valid => {
        const errorMsg = this.validateForm()
        if (errorMsg) {
          this.$message(errorMsg);
          return false;
        }

        if (valid) {
          var goodsCombinationLists = [];
          this.CommodityFormList.goodsCombinationList.map(child => {
            console.log(child, "child");
            goodsCombinationLists.push({
              zuGoodsId: child.zuGoodsId,
              zuGoodsName: child.zuGoodsName,
              zuSkuCode: item.skuCode,
              zuUpc: item.upc,
              zuGoodsState: item.goodsState,
              zuPrice: item.price * 100,
              zuSpecs: child.zuSpecs
            });
          });
          var piclist = [];
          item.pics.map(child => {
            piclist.push(child.url);
          });
          var str = [];
          this.cakelist.map(parent => {
            parent.children.map(child => {
              if (item.categoryId === child.value) {
                str.push(parent);
              }
            });
          });

          //组合商品新增提交
          const params = {
            parentCategoryId: str[0].value,
            categoryName: str[0].label,
            deptId: this.goodsInfo.deptId ? this.goodsInfo.deptId :
                    (this.clickFramingchecked == true ? "1" : this.cityareaId),
            name: item.name,
            categoryId: item.categoryId,
            materialId: this.materialslistValue,
            mainPic: item.mainPic,
            pics: piclist,
            description: item.description,
            isCombination: 2,
            goodsSkuRequests: [],
            goodsCombinationRequests: goodsCombinationLists
          };
          addGoods(params).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: "添加商品",
                message: "添加商品成功",
                type: "success",
                duration: 2000
              });
              this.dialogCommodityVisible = false;
              this.selectedValue = [];
              this.materialslistValue = [];
              this.$emit('getList')
            } else {
              this.$notify({
                title: "sku码重复",
                message: "sku码重复!请重新填写",
                type: "success",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    updatecommodityData(item, verification) {
      this.$refs[verification].validate(valid => {
        if (valid) {
          const errorMsg = this.validateForm()
          if (errorMsg) {
            this.$message(errorMsg);
            return false;
          }
          //组合商品编辑提交
          var goodsCombinationLists = [];
          this.CommodityFormList.goodsCombinationList.map(child => {
            console.log(child, "child");
            goodsCombinationLists.push({
              zuSkuId: child.zuSkuId,
              zuGoodsId: child.zuGoodsId,
              zuGoodsName: child.zuGoodsName,
              zuSkuCode: item.skuCode,
              zuUpc: item.upc,
              zuGoodsState: item.goodsState,
              zuPrice: item.price * 100,
              zuSpecs: child.zuSpecs
            });
          });
          var piclist = [];
          item.pics.map(child => {
            piclist.push(child.url);
          });

          var str = [];
          this.cakelist.map(parent => {
            parent.children.map(child => {
              if (item.categoryId === child.value) {
                str.push(parent);
              }
            });
          });

          const commodityData = {
            deptId: this.goodsInfo.deptId,
            parentCategoryId: str[0].value,
            categoryName: str[0].label,
            id: item.id,
            name: item.name,
            categoryId: item.categoryId,
            materialId: this.materialslistValue,
            mainPic: item.mainPic,
            pics: piclist,
            description: item.description,
            isCombination: 2,
            goodsSkuRequests: [],
            goodsCombinationRequests: goodsCombinationLists,
            isOnSale: 1
          };
          goodsUpdate(commodityData).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: "修改商品",
                message: "修改商品成功",
                type: "success",
                duration: 2000
              });
              this.dialogCommodityVisible = false;
              this.$emit('getList')
            } else {
              this.$notify({
                title: "sku码重复",
                message: "sku码重复!请重新填写",
                type: "success",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    validateForm() {
      const item = this.CommodityFormList
      if (this.materialsShow && this.materialslistValue && this.materialslistValue.length == 0) {
        return '请选择蛋糕原料';
      }
      if (!item.categoryId) {
        return '请选择蛋糕类型';
      }
      if (!item.price) {
        return '定价必填';
      }
      if (!this.CommodityFormList.goodsCombinationList || !this.CommodityFormList.goodsCombinationList.length) {
        return '组合商品及sku不为空';
      }
      if (!item.skuCode) {
        return 'sku码必填';
      }
      if (!item.price) {
        return '定价必填';
      }
    },
    getGoodsMaterial() {
      //商品原料
      GoodsMaterial("").then((response) => {
        const batchdata = response.data.data;
        const dataValueBatch = (batchdata) =>
          batchdata.map(({ id, materialName, children }) =>
            children
              ? {
                value: id,
                label: materialName,
                children: dataValueBatch(children),
                disabled: true,
              }
              : {
                value: id,
                label: materialName,
              }
          );
        this.materialslist = dataValueBatch(batchdata);
      });
    },
    handlematerialzhName(values, item) {
      if (this.checkedmaterialslist.length >= 10) {
        this.$message({
          message: "该商品原料最多可添加10个",
          type: "warning"
        });
        return false;
      } else {
        const SelectedmaterialsList = [];
        item.map(child => {
          SelectedmaterialsList.push({
            materialId: child.value,
            materialName: child.label,
            parentId: child.parentId
          });
        });
        this.checkedmaterialslist = SelectedmaterialsList;
      }
    },
    handlegoodListClose(tag, index) {
      this.CommodityFormList.goodsCombinationList.splice(index, 1);
    },
  },
  mounted() {
    var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
    this.cityareaId = saberareaIds["content"];
    this.getGoodsMaterial()
  }
};
</script>
<style lang="scss" scoped>
::v-deep .specificationsslist {
  border: 1px solid #dcdfe6;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin: 5px 0;
  width: 400px;
  height: 200px;
  position: absolute;
  width: 100%;
  z-index: 999;

  .el-tabs--left .el-tabs__header.is-left {
    width: 80%;
  }

  .close {
    position: absolute;
    top: 0;
    right: 10px;
    cursor: pointer;
  }

  .el-checkbox-group {
    display: flex;
    flex-direction: column;
    padding: 10px 0;
    background-origin: padding-box;
    line-height: 30px;
    height: 170px;
    overflow: hidden;
    overflow-y: scroll;

    .el-radio {
      line-height: 30px;
    }
  }
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>